package nl.hva.web.mvcwebapp.controllers;

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
import nl.hva.web.mvcwebapp.models.Course;
import nl.hva.web.mvcwebapp.service.HibernateUtil;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.servlet.annotation.MultipartConfig;
import nl.hva.web.mvcwebapp.classes.UploadClass;
import nl.hva.web.mvcwebapp.doa.AssignmentDAO;
import nl.hva.web.mvcwebapp.doa.ChapterDAO;
import nl.hva.web.mvcwebapp.doa.CourseDAO;
import nl.hva.web.mvcwebapp.doa.TestDAO;
import nl.hva.web.mvcwebapp.doa.UploadAssignmentDAO;
import nl.hva.web.mvcwebapp.doa.UserDAO;
import nl.hva.web.mvcwebapp.models.Assignment;
import nl.hva.web.mvcwebapp.models.Chapter;
import nl.hva.web.mvcwebapp.models.News;
import nl.hva.web.mvcwebapp.models.Test;
import nl.hva.web.mvcwebapp.models.UploadAssignment;
import nl.hva.web.mvcwebapp.models.UploadedAssignments;
import nl.hva.web.mvcwebapp.models.User;
import nl.hva.web.mvcwebapp.models.UserTest;

@MultipartConfig
public class UploadAssignmentController extends HttpServlet {

    private String address = "/assignments.jsp";
    ArrayList paths_jsp = new ArrayList();
    ArrayList paths = new ArrayList();
    public static HttpSession session_user;
    /*
     * HTTP GET request
     */

    public ArrayList getPaths() {
        ArrayList paths = new ArrayList();
        paths.add(0, "/chapter/uploadassignments");
        paths.add(1, "/chapter/uploadassignment/new");
        paths.add(2, "/chapter/uploadassignment/edit");
        paths.add(3, "/chapter/uploadedassignment/view");
        paths.add(4, "/chapter/uploadedassignment/new");
        paths.add(5, "/chapter/uploadedassignment/approve");
        paths.add(6, "/chapter/uploadedassignment/adminview");
        //paths.add(5, "/chapter/test");
        //paths.add(6, "/chapter/test/new");
        //paths.add(7, "/chapter/test/edit");
        //paths.add(8, "/chapter/test/score");
        return paths;
    }

    public ArrayList getPathsJSP() {
        ArrayList paths_jsp = new ArrayList();
        paths_jsp.add(0, "/uploadassignment/uploadassignment.jsp");
        paths_jsp.add(1, "/uploadassignment/uploadassignment_edit.jsp");
        paths_jsp.add(2, "/uploadassignment/uploadassignment_edit.jsp");
        paths_jsp.add(3, "/uploadassignment/uploadedassignment_view.jsp");
        paths_jsp.add(4, "/uploadassignment/uploadedassignment_view.jsp");
        paths_jsp.add(5, "/uploadassignment/uploadedassignment_view.jsp");
        paths_jsp.add(6, "/uploadassignment/uploadedassignments.jsp");
//        paths_jsp.add(3, "/assignment/assignment_edit.jsp");
//        paths_jsp.add(4, "/assignment/assignments.jsp");
//        paths_jsp.add(5, "/test/test.jsp");
//        paths_jsp.add(6, "/test/test_edit.jsp");
//        paths_jsp.add(7, "/test/test_edit.jsp");
//        paths_jsp.add(8, "/test/test-score.jsp");


        return paths_jsp;
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        boolean redirect = false;
        ArrayList paths = getPaths();
        ArrayList paths_jsp = getPathsJSP();
        String path = request.getServletPath();


        for (int i = 0; i < paths.size(); i++) {
            try {
                if (path.equals(paths.get(i).toString())
                        || path.substring(0, path.toString().length() - 1).equals(paths.get(i).toString())) {
                    // /chapter/uploadassignments
                    System.out.println(i);
                    if (i == 0) {
                        HttpSession session_user = request.getSession(true);
                        String firstname = (String) session_user.getAttribute("user_firstname");
                        int user_id = 0;
                        if (firstname != null) {
                            user_id = Integer.valueOf("" + session_user.getAttribute("user_id"));
                        }
                        int chapterid = Integer.parseInt(request.getParameter("chapterid"));
                        Chapter chapter = ChapterDAO.getChapter(chapterid);
                        List<UploadedAssignments> documentlist = UploadAssignmentDAO.getAllDocumentsForUser(chapter.getChapterid(), user_id);
                        
                        List<UploadAssignment> assignments = UploadAssignmentDAO.getAllAssignments(chapter.getChapterid());
                        request.setAttribute("assignments", assignments);
                        request.setAttribute("documents", documentlist);
                        request.setAttribute("chapter", chapter);

                    }// /chapter/uploadassignments/new
                    else if (i == 1) {
                        int chapterid = Integer.parseInt(request.getParameter("chapterid"));
                        Chapter chapter = ChapterDAO.getChapter(chapterid);

                        request.setAttribute("chapter", chapter);
                        request.setAttribute("pageTitle", "New Upload Assignment");
                        request.setAttribute("buttonTitle", "Add");
                    }// /chapter/uploadassignments/edit
                    else if (i == 2) {
                        int uploadassignmentid = Integer.parseInt(request.getParameter("uploadassignmentid"));
                        UploadAssignment uploadassignment = UploadAssignmentDAO.getUploadAssignment(uploadassignmentid);
                        request.setAttribute("assignment", uploadassignment);
                        request.setAttribute("pageTitle", "Edit Upload Assignment");
                        request.setAttribute("buttonTitle", "Edit");
                    } // /chapter/uploadedassignment/view
                    else if (i == 3) {
                        int documentid = Integer.parseInt(request.getParameter("documentid"));
                        UploadedAssignments document = UploadAssignmentDAO.getDocument(documentid);
                        request.setAttribute("assignment", document.getUploadassignment());
                        request.setAttribute("document", document);
                    }// /chapter/uploadedassignment/new
                    else if (i == 4) {
                        int uploadassignmentid = Integer.parseInt(request.getParameter("uploadassignmentid"));
                        UploadAssignment uploadassignment = UploadAssignmentDAO.getUploadAssignment(uploadassignmentid);
                        request.setAttribute("assignment", uploadassignment);
                    }// /test/new
                    else if (i == 5) {
                    }// /test/edit
                    /*else if (i == 7) {
                     int testid = Integer.parseInt(request.getParameter("testid"));
                     Test test = TestDAO.getTest(testid);
                     request.setAttribute("test", test);
                     request.setAttribute("pageTitle", "New Test");
                     request.setAttribute("buttonTitle", "Edit");
                     }// /test/score
                     else if (i == 8) {
                     int testid = Integer.parseInt(request.getParameter("testid"));
                     List<UserTest> usertest = TestDAO.getUserTest(testid);
                     request.setAttribute("testscore", usertest.get(0));
                     request.setAttribute("pageTitle", "New Test");
                     request.setAttribute("buttonTitle", "Edit");
                     }*/ else if (i == 6) {
                        int chapterid = Integer.parseInt(request.getParameter("chapterid"));
                        Chapter chapter = ChapterDAO.getChapter(chapterid);
                        List<UploadedAssignments> uploadassignmentlist = UploadAssignmentDAO.getAllUploadAssignments(chapterid);
                        request.setAttribute("chapter", chapter);
                        request.setAttribute("assignments", uploadassignmentlist);
                        request.setAttribute("amountchapters", uploadassignmentlist.size());
                    }
                    address = paths_jsp.get(i).toString();
                }
            } catch (Exception E) {
            }
        }

        request.setAttribute("path", path);
        if (!redirect) {
            RequestDispatcher dispatcher = request.getRequestDispatcher(address);
            dispatcher.forward(request, response);
        }

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        ArrayList paths = getPaths();
        ArrayList paths_jsp = getPathsJSP();
        // Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        //Transaction tx = session.beginTransaction();
        session_user = request.getSession();
        String path = request.getServletPath();
        for (int i = 0; i < paths.size(); i++) {
            try {
                if (path.equals(paths.get(i).toString())
                        || path.substring(0, path.toString().length() - 1).equals(paths.get(i).toString())) {
                    address = paths_jsp.get(i).toString();
                    // /Insert Test
                    System.out.println(i);
                    if (i == 0) {
                    }// ---------------- /assignment/new --------------------
                    else if (i == 1) {
                        int chapterid = Integer.parseInt(request.getParameter("chapterid"));
                        Chapter chapter = ChapterDAO.getChapter(chapterid);
                        UploadAssignmentDAO.insertUploadAssignment(request, chapter);
                        response.sendRedirect(response.encodeRedirectURL("../../chapter/uploadassignments?chapterid=" + chapterid));
                    }// --------------- /assignment/edit --------------------
                    else if (i == 2) {
                        int assignmentid = Integer.parseInt(request.getParameter("assignmentid"));
                        UploadAssignment assignment = UploadAssignmentDAO.getUploadAssignment(assignmentid);
                        System.out.println("TEST....");
                        UploadAssignmentDAO.updateUploadAssignment(request, assignment);
                        response.sendRedirect(response.encodeRedirectURL("../../chapter/uploadassignments?chapterid=" + assignment.getChapter().getChapterid()));

                    }// /chapter/uploadedassignment/view
                    else if (i == 3) {
                        System.out.println("VIEW");
                        int uploadassignmentid = Integer.parseInt(request.getParameter("documentid"));
                        UploadedAssignments document = UploadAssignmentDAO.getDocument(uploadassignmentid);
                        HttpSession session_user = request.getSession(true);
                        String firstname = (String) session_user.getAttribute("user_firstname");
                        int user_id = 0;
                        if (firstname != null) {
                            user_id = Integer.valueOf("" + session_user.getAttribute("user_id"));
                        }
                        User user = UserDAO.getUser(user_id);

                        // ********************** Upload Document *****************************
                        Part filePart = request.getPart("file");
                        UploadClass upload = new UploadClass();
                        //Create folder in /images
                        String folder = "uploadeddocuments";
                        String path_in_server = upload.doUpload(filePart, folder, request, response);
                        // ********************** END Upload Document *************************
                        request.setAttribute("path_in_server", path_in_server);

                        UploadAssignmentDAO.updateDocument(request, document, user);
                        response.sendRedirect(response.encodeRedirectURL("../../chapter/uploadassignments?chapterid=" + document.getUploadassignment().getChapter().getChapterid()));
                    } // /chapter/uploadedassignment/new
                    else if (i == 4) {
                        System.out.println("NEW");
                        int documentid = Integer.parseInt(request.getParameter("uploadassignmentid"));
                        UploadAssignment assignment = UploadAssignmentDAO.getUploadAssignment(documentid);
                        HttpSession session_user = request.getSession(true);
                        String firstname = (String) session_user.getAttribute("user_firstname");
                        int user_id = 0;
                        if (firstname != null) {
                            user_id = Integer.valueOf("" + session_user.getAttribute("user_id"));
                        }
                        User user = UserDAO.getUser(user_id);

                        // ********************** Upload Document *****************************
                        Part filePart = request.getPart("file");
                        UploadClass upload = new UploadClass();
                        //Create folder in /images
                        String folder = "uploadeddocuments";
                        String path_in_server = upload.doUpload(filePart, folder, request, response);
                        // ********************** END Upload Document *************************
                        request.setAttribute("path_in_server", path_in_server);

                        UploadAssignmentDAO.insertDocument(request, assignment, user);
                        response.sendRedirect(response.encodeRedirectURL("../../chapter/uploadassignments?chapterid=" + assignment.getChapter().getChapterid()));
                    }// /test/edit
                    else if (i == 5) {
                        int documentid = Integer.parseInt(request.getParameter("documentid"));
                        UploadedAssignments document = UploadAssignmentDAO.approveAssignment(documentid);
                        if (Integer.parseInt(request.getParameter("admin")) == 1) {
                            response.sendRedirect(response.encodeRedirectURL("../../chapter/uploadassignments?chapterid=" + document.getUploadassignment().getChapter().getChapterid()));
                        } else {
                            response.sendRedirect(response.encodeRedirectURL("../../chapter/uploadedassignment/adminview?chapterid=" + document.getUploadassignment().getChapter().getChapterid()));
                        }
                    }
                }
            } catch (Exception E) {
            }
        }

    }
}
